package com.example.administrator.newxlmedical;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.baseproject.BaseActivity;
import com.irisian.irissdk.IrisSdk;
import com.jauker.widget.BadgeView;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

import adapters.MainViewPagerAdapter;
import beans.NewUserInfoBean;
import beans.OperateGoodsDetailsBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import dialogs.FasterOpenDoorDialog;
import fragments.MenuFragmet;
import fragments.MenuSecondFragment;
import singleton.SingletonClass;
import utils.ActivityControl;
import utils.ActivityUtil;
import utils.CustomSharedPreferencePath;
import utils.FormateUtils;
import utils.NetUtil;
import utils.ObjectSaveUtil;
import utils.TimeUtil;
import utils.ToastUtil;

public class MainActivity extends BaseActivity {
    @BindView(R.id.vp_main)
    ViewPager viewPager;
    @BindView(R.id.tv_main_date)
    TextView tvDate;
    @BindView(R.id.tv_main_time)
    TextView tvTime;
    @BindView(R.id.tv_main_user_info)
    TextView tvUserInfo;
    @BindView(R.id.tv_main_timeout_warn)
    TextView tvTimeoutWarn;
    @BindView(R.id.tv_main_stock_warn)
    TextView tvStockWarn;
    @BindView(R.id.tv_main_no_return_warn)
    TextView tvNoReturnWarn;
    @BindView(R.id.iv_main_toright)
    ImageView ivToright;
    @BindView(R.id.iv_main_toleft)
    ImageView ivToleft;
    @BindView(R.id.iv_main_first_menu)
    ImageView ivFirstMenu;
    @BindView(R.id.iv_main_second_menu)
    ImageView ivSecondMenu;
    MainViewPagerAdapter viewPagerAdapter;
    @BindView(R.id.tv_main_img_head)
    ImageView ivIcon;
    @BindView(R.id.iv_main_logo)
    ImageView ivMainLogo;
    @BindView(R.id.bv_main_timeout_new_warn)
    BadgeView bvTimeoutNewWarn;
    @BindView(R.id.bv_main_stock_new_warn)
    BadgeView bvStockNewWarn;
    @BindView(R.id.bv_main_no_return_new_warn)
    BadgeView bvNoReturnNewWarn;
    @BindView(R.id.bv_main_error_goods)
    BadgeView bvMainErrorGoods;
    @BindView(R.id.tv_main_no_error_goods)
    TextView tvMainNoErrorGoods;
    @BindView(R.id.tv_main_wifi)
    TextView tvWifi;
    @BindView(R.id.iv_main_wifi)
    ImageView ivWifi;

    private List<Fragment> fragmentList = new ArrayList<>();
    private int maxCount = 99;
    //    private InputMethodManager imm;
    //是否开门,开门的时候,不能有屏保
    private boolean isOpenDoor = false;
    private MyHandler allHandler = SingletonClass.getSingleton(MyHandler.class);
    private SharedPreferences sharedPreferences;
    private int error_goods_count = 0;
    private SharedPreferences.Editor edit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 快捷开门
        if (Constants.IS_SHOW_FASTER_OPENDOOR) {
            new FasterOpenDoorDialog(this, R.style.dialog).show();
        }

        // 设置wifi信号
        setWifi();

        getErrorGoodsSize();
    }

    @Override
    public void initView() {
        super.initView();
        if (IrisSdk.isInitialized()) {
            IrisSdk.stopReadDistance(this);
            IrisSdk.closeCamera(this);
            IrisSdk.releaseSdk(this);
        }
        ToastUtil.hideToast();

        allHandler.removeMessages(HandlerConstant.NO_OPERATION);
        allHandler.sendEmptyMessageDelayed(HandlerConstant.NO_OPERATION, Constants.TIME_OUT);

        NewUserInfoBean.DataBean dataBean = (NewUserInfoBean.DataBean) ObjectSaveUtil.readObject(this, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
        sharedPreferences = ActivityUtil.getSharedPreferences(MainActivity.this);
        //  获取设置的锁屏时间
        if (sharedPreferences != null) {
            timeout = Integer.valueOf(sharedPreferences.getString(Constants.LOCK_SCREEN + dataBean.getID(), "60")) * 1000;
        }

        // 设置对应的用户icon
        if (dataBean != null) {
            tvUserInfo.setText(dataBean.getName() + "/" + FormateUtils.getRole(dataBean.getRoleInfoId()) + "/" + dataBean.getDepartment());
            if (dataBean.getRoleInfoId() == Constants.ROLE_NURSE) { //护士
                ivIcon.setImageResource(R.mipmap.role_nurse);
            } else if (dataBean.getRoleInfoId() == Constants.ROLE_HEAD_NURSE) { //护士长
                ivIcon.setImageResource(R.mipmap.role_head_nurse);
            } else if (dataBean.getRoleInfoId() == Constants.ROLE_MANAGE) { //高层管理
                ivIcon.setImageResource(R.mipmap.role_manage);
            } else if (dataBean.getRoleInfoId() == Constants.ROLE_FACTORY) { //供应商
                ivIcon.setImageResource(R.mipmap.role_supplier);
            } else { //厂商
                ivIcon.setImageResource(R.mipmap.role_supplier);
            }
        }

        // 设置红点提示
        getErrorGoodsSize();

        int timeout_count = sharedPreferences.getInt(Constants.TIMEOUT_COUNT, 0);
        int inventory_count = sharedPreferences.getInt(Constants.INVENTORY_COUNT, 0);
        int returnHine_count = sharedPreferences.getInt(Constants.RETURNHINT_COUNT, 0);

        edit = sharedPreferences.edit();

        Log.e(TAG, "timeout_count = " + timeout_count + "  inventory_count = " + inventory_count + "  returnHine_count = " + returnHine_count);
        if (timeout_count != 0) {
            if (timeout_count > maxCount) {
                bvTimeoutNewWarn.setText("99+", TextView.BufferType.NORMAL);
            } else {
                bvTimeoutNewWarn.setBadgeCount(timeout_count);
            }
        }

        bvTimeoutNewWarn.setBackgroundResource(R.mipmap.bubble_new);

        if (inventory_count != 0) {
            if (inventory_count > maxCount) {
                bvStockNewWarn.setText("99+", TextView.BufferType.NORMAL);
            } else {
                bvStockNewWarn.setBadgeCount(inventory_count);
            }
        }
        bvStockNewWarn.setBackgroundResource(R.mipmap.bubble_new);

        if (returnHine_count != 0) {
            if (returnHine_count > maxCount) {
                bvNoReturnNewWarn.setText("99+", TextView.BufferType.NORMAL);
            } else {
                bvNoReturnNewWarn.setBadgeCount(returnHine_count);
            }
        }
        bvNoReturnNewWarn.setBackgroundResource(R.mipmap.bubble_new);

        bvMainErrorGoods.setBackgroundResource(R.mipmap.bubble_new);

        initTime(0);
        MenuFragmet menuFragmet = new MenuFragmet();
        MenuSecondFragment menuSecondFragment = new MenuSecondFragment();
        fragmentList.add(menuFragmet);
        fragmentList.add(menuSecondFragment);
        viewPagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(viewPagerAdapter);

    }

    private void setWifi() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        int strength = WifiManager.calculateSignalLevel(info.getRssi(), 5);
        Log.e(TAG, "setWifi: " + strength);
        int i = 0;
        switch (strength) {
            case 0:
                break;
            case 1:
                i = 1;
                ivWifi.setImageResource(R.mipmap.wifi1);
                break;
            case 2:
                i = 2;
                ivWifi.setImageResource(R.mipmap.wifi2);
                break;
            case 3:
                i = 3;
                ivWifi.setImageResource(R.mipmap.wifi3);
                break;
            case 4:
                i = 4;
                ivWifi.setImageResource(R.mipmap.wifi4);
                break;
        }

        if (!Constants.IS_FUYI) {
            if (i == 0) {
                tvWifi.setVisibility(View.VISIBLE);
                ivWifi.setVisibility(View.GONE);
            } else {
                tvWifi.setVisibility(View.GONE);
                ivWifi.setVisibility(View.VISIBLE);
            }
        } else {
            int netWorkState = NetUtil.getNetWorkState(this);
            ivWifi.setVisibility(View.VISIBLE);
            tvWifi.setVisibility(View.GONE);
            if (netWorkState == -1) {
                ivWifi.setImageResource(R.mipmap.disconnect);
            } else {
                ivWifi.setImageResource(R.mipmap.link);
            }
        }


    }

    private void getErrorGoodsSize() {
        Map<String, OperateGoodsDetailsBean.DataBean> recordList = (Map<String, OperateGoodsDetailsBean.DataBean>) CustomSharedPreferencePath.getData(this, Constants.RECORD_ERROR_GOODS, null);
        int count = 0;
        if (recordList != null) {
            Set<Map.Entry<String, OperateGoodsDetailsBean.DataBean>> entries = recordList.entrySet();
            Iterator<Map.Entry<String, OperateGoodsDetailsBean.DataBean>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry mapentry = iterator.next();
                OperateGoodsDetailsBean.DataBean value = (OperateGoodsDetailsBean.DataBean) mapentry.getValue();
                if (value.getNumber() > 0) {
                    count += value.getNumber();
                }
            }
            error_goods_count = count;
            bvMainErrorGoods.setBadgeCount(count);
        } else {
            bvMainErrorGoods.setBadgeCount(0);
        }
    }

    @Override
    protected void setListener() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    initUI(viewPager.getCurrentItem());
                }
            }
        });
    }

    @OnClick({R.id.tv_main_timeout_warn, R.id.tv_main_stock_warn, R.id.tv_main_no_return_warn, R.id.iv_main_toright,
            R.id.iv_main_toleft, R.id.iv_main_first_menu, R.id.iv_main_second_menu, R.id.tv_main_no_error_goods})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_main_timeout_warn:
                ActivityUtil.jumpToActivity(MainActivity.this, TimeOutActivity.class);
                break;
            case R.id.tv_main_stock_warn:
                ActivityUtil.jumpToActivity(MainActivity.this, InventoryWarningActivity.class);
                break;
            case R.id.tv_main_no_return_warn:
                ActivityUtil.jumpToActivity(MainActivity.this, ReturnHintActivity.class);
                break;
            case R.id.tv_main_no_error_goods:
                ActivityUtil.jumpToActivity(MainActivity.this, ErrorGoodsActivity.class);
                break;
            case R.id.iv_main_toright:
                slideMenu(1);
                break;
            case R.id.iv_main_toleft:
                slideMenu(0);
                break;
            case R.id.iv_main_first_menu:
                slideMenu(0);
                break;
            case R.id.iv_main_second_menu:
                slideMenu(1);
                break;
        }
    }

    public void slideMenu(int currentItem) {
        if (viewPager.getCurrentItem() != currentItem) {
            viewPager.setCurrentItem(currentItem);
            initUI(currentItem);
        }
    }

    public void initUI(int currentItem) {
        if (currentItem == 0) {
            ivFirstMenu.setImageResource(R.mipmap.menu_first_select);
            ivSecondMenu.setImageResource(R.mipmap.menu_second_unselect);
            ivToright.setVisibility(View.VISIBLE);
            ivToleft.setVisibility(View.GONE);
        } else {
            ivFirstMenu.setImageResource(R.mipmap.menu_first_unselect);
            ivSecondMenu.setImageResource(R.mipmap.menu_second_select);
            ivToright.setVisibility(View.GONE);
            ivToleft.setVisibility(View.VISIBLE);
        }
    }

    private void initTime(int time) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();

        String format = dateFormat.format(date);
        tvTime.setText(format.substring(11, 16));

        Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));

        tvDate.setText(format.substring(0, 10));
        String s = format.substring(17, 19);
        if (time == 0) {
            time = (60 - Integer.parseInt(s)) * 1000;
        }

        sendEmptyMessageDelay(HandlerConstant.INIT_TIME_SUCCESS, time);
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case HandlerConstant.BEGIN_INVENTORY:
            case HandlerConstant.TAKE_OUT:
            case HandlerConstant.CHECK:
            case HandlerConstant.CHECK_AGAIN:
                isOpenDoor = true;
                allHandler.removeMessages(HandlerConstant.NO_OPERATION);
                break;
            case HandlerConstant.END_INVENTORY:
            case HandlerConstant.CLOSE_DOOR:
                Log.e("GGG", "CLOSE_DOOR ");
                isOpenDoor = false;
                allHandler.sendEmptyMessageDelayed(HandlerConstant.NO_OPERATION, Constants.TIME_OUT);
                break;
            case HandlerConstant.INIT_TIME_SUCCESS:
                initTime(60000);
                break;

            case HandlerConstant.NO_OPERATION:
                Log.e("GGG", "NO_OPERATION " + !isOpenDoor + "   " + Constants.TIME_OUT);

                // 重置批次号
                String string = sharedPreferences.getString(Constants.THE_DAY, "null");
                if (!string.equals(TimeUtil.getShowDate())) {
                    edit.putInt(Constants.COMBO_BATCH_NUMBER, 1);
                    edit.putString(Constants.THE_DAY, TimeUtil.getShowDate());
                }

                edit.commit();

                if (Constants.IS_FUYI) {
                    if (!isOpenDoor) {
                        if (!Constants.CHECKING) {  // 是否正在验收中
                            ActivityUtil.jumpToActivity(MainActivity.this, EnterActivity.class);
                            ActivityControl.finishAll();
                        }
                    }
                } else {
                    ActivityUtil.jumpToActivity(MainActivity.this, ScreensaverActivity.class);
                    ActivityControl.finishAll();
                }
                break;

            case HandlerConstant.STORAGEWARNING_MODIFY:
                boolean obj = (boolean) msg.obj;
                Integer badgeCount = bvStockNewWarn.getBadgeCount();
                if (obj) {
                    bvStockNewWarn.setBadgeCount(badgeCount + 1);
                    edit.putInt(Constants.INVENTORY_COUNT, badgeCount + 1);
                } else {
                    if (badgeCount - 1 > 0) {
                        bvStockNewWarn.setBadgeCount(badgeCount - 1);
                        edit.putInt(Constants.INVENTORY_COUNT, badgeCount - 1);
                    } else {
                        bvStockNewWarn.setBadgeCount(0);
                        edit.putInt(Constants.INVENTORY_COUNT, 0);
                    }
                }
                edit.commit();
                break;

            case HandlerConstant.RED_COUNT:
                int timeout = msg.arg1;
                int warn = msg.arg2;
                int returnHint = (int) msg.obj;
                if (timeout < 99) {
                    bvTimeoutNewWarn.setBadgeCount(timeout);
                }else {
                    bvTimeoutNewWarn.setText("99+", TextView.BufferType.NORMAL);
                }
                if (warn < 99) {
                    bvStockNewWarn.setBadgeCount(warn);
                }else {
                    bvStockNewWarn.setText("99+", TextView.BufferType.NORMAL);
                }

                if (returnHint < 99){
                    bvNoReturnNewWarn.setBadgeCount(returnHint);
                }else {
                    bvNoReturnNewWarn.setText("99+", TextView.BufferType.NORMAL);
                }

                edit.putInt(Constants.TIMEOUT_COUNT, timeout);
                edit.putInt(Constants.INVENTORY_COUNT, warn);
                edit.putInt(Constants.RETURNHINT_COUNT, returnHint);
                edit.commit();
                break;

            case HandlerConstant.ERROR_MODIFY:
                getErrorGoodsSize();
                edit.putInt(Constants.ERRORGOODS_COUNT, error_goods_count);
                break;
            case HandlerConstant.NETWORK_NONE:
            case HandlerConstant.NETWORK_REFRESH:
                setWifi();
                break;
            case HandlerConstant.SERIALPORT_ERROR:
                String errorType = (String) msg.obj;
                if (errorType.equals("03")) {
                    ToastUtil.showToast(this, "03 获取版本号失败!");
                } else if (errorType.equals("0C")) {
                    ToastUtil.showToast(this, "0C 获取当前正在运行的程序失败!");
                } else if (errorType.equals("04")) {
                    ToastUtil.showToast(this, "04 启动应用程序失败!");
                } else if (errorType.equals("92")) {
                    ToastUtil.showToast(this, "92 设置读取功率失败!");
                } else if (errorType.equals("9B")) {
                    ToastUtil.showToast(this, "9B GEN2 设置失败!");
                } else if (errorType.equals("97")) {
                    ToastUtil.showToast(this, "97 设置频段失败!");
                } else if (errorType.equals("93")) {
                    ToastUtil.showToast(this, "97 设置协议失败!");
                } else if (errorType.equals("91")) {
                    ToastUtil.showToast(this, "91 天线设置失败!");
                } else if (errorType.equals("62")){
                    ToastUtil.showToast(this, "62 获取读取功率范围失败!");
                }
                break;

            case HandlerConstant.RFID_SUM:
                int s = (int) msg.obj;
                Log.e("AAA", "RFID_SUM: " + s + "  " + Constants.CHECK_LOG);
                if (Constants.CHECK_LOG) {
                    Toast.makeText(MainActivity.this,"读到 " + s + " RFID标签",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

}
